package org.example.practiceexamples.controller;


import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.practiceexamples.component.JWTComponent;
import org.example.practiceexamples.dox.ModifyPassword;
import org.example.practiceexamples.dox.User;
import org.example.practiceexamples.exception.Code;
import org.example.practiceexamples.repository.UserRepository;
import org.example.practiceexamples.service.TeacherService;
import org.example.practiceexamples.vo.ResultVO;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@CrossOrigin(exposedHeaders = "token")
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/")
public class LoginController {

    private final TeacherService teacherService;
    private final PasswordEncoder passwordEncoder;
    private final JWTComponent jwtComponent;
    private final UserRepository userRepository;
    private String account;

    @PostMapping("login")
    public ResultVO login(@RequestBody User user, HttpServletResponse response) {
        account=user.getAccount();
        String uid = userRepository.findIdByAccount(account);
        String password = teacherService.findPasswordByAccount(account);
        if (password == null || !passwordEncoder.matches(user.getPassword(),password)) {
            return ResultVO.error(Code.LOGIN_ERROR);
        }
        String token = jwtComponent.encode(Map.of("uid",uid,
                "role",teacherService.findUserByAccount(account).getRole()));

        //响应式响应对象
        response.setHeader("token", token);
        response.setHeader("role",teacherService.findUserByAccount(account).getRole());
        return ResultVO.success(account,"登陆成功！");
    }
//
    @PostMapping("modifypwd")
    public ResultVO modifypwd(@RequestBody ModifyPassword mPwd, HttpServletResponse response,@RequestAttribute String uid) {

        String pwd = teacherService.findUserbyId(uid).getPassword();
        if(passwordEncoder.matches(mPwd.getOldPassword(),pwd)){
            String encodedPassword = passwordEncoder.encode(mPwd.getNewPassword());
            teacherService.updatePassword(uid,account,encodedPassword);
            return ResultVO.success(account,"修改成功！");
        }
        else{
            return ResultVO.error(Code.ERROR,"旧密码输入错误！");
        }
    }
}
